package cn.car91.activity;

import java.io.Serializable;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import cn.car91.R;
import cn.car91.adapter.RepairShopListAdapter;
import cn.car91.bean.RepairShop;
import cn.car91.pager.AroundPager;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.utils.EarthUtil;
import cn.car91.utils.EarthUtil.Location;
import cn.car91.view.FooterView.Item;
import cn.car91.view.HerilyAlertDialog.Builder;
import cn.car91.view.XListView;
import cn.car91.view.XListView.IXListViewListener;
import cn.car91.view.XListViewFooter;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;

public class AroundMainActivity extends BaseActivity {
    LocationClient locationClient;
    LocationClientOption option;

    @ViewInject(R.id.around_list)
    XListView aroundList;
    @ViewInject(R.id.none)
    View none;

    Boolean addDate = false;
    RepairShopListAdapter repairShopListAdapter = null;
    AroundPager aroundPager = new AroundPager();
    Double lat;
    Double lon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_around_main);
        super.onCreate(savedInstanceState);

        repairShopListAdapter = new RepairShopListAdapter(this, R.layout.view_repairshop_item);
        aroundList.setAdapter(repairShopListAdapter);

        //设置定位条件
        option = getCar91Application().getLocationOption();
        option.setScanSpan(getCar91Application().UPDATE_TIME_SHORT);    //设置定时定位的时间间隔。单位毫秒

        locationClient = getCar91Application().getmLocationClient();
        locationClient.setLocOption(option);
        locationClient.registerLocationListener(bdLocationLinstener);
        locationClient.requestOfflineLocation();

        try {
            lat = locationClient.getLastKnownLocation().getLatitude();
            lon = locationClient.getLastKnownLocation().getLongitude();
        } catch (Exception e) {
        }

        //scrollView.setOnTouchListener(onScrollTouchListener);
        aroundList.setPullLoadEnable(true);
        aroundList.setPullRefreshEnable(true);
        aroundList.setXListViewListener(onAroundViewListener);

        registerReceiver(itemChangeBroadcastReceiver, new IntentFilter(MainFragmentActivity.naviAction));
    }

    private IXListViewListener onAroundViewListener = new IXListViewListener() {
        @Override
        public void onRefresh() {
            addDate = false;
            aroundPager.reset();
            aroundList.getmFooterView().setState(XListViewFooter.STATE_NORMAL);
            getData();
        }

        @Override
        public void onLoadMore() {
            addDate = true;
            getData();
        }
    };

    /**
     * 停止刷新，
     */
    private void onStopLoad() {
        aroundList.stopRefresh();
        aroundList.stopLoadMore();
        aroundList.setRefreshTime("刚刚");
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        option.setScanSpan(getCar91Application().UPDATE_TIME_SHORT);
        locationClient.setLocOption(option);

        if (!locationClient.isStarted())
            locationClient.start();

        if (locationClient.isStarted())
            locationClient.requestOfflineLocation();
        super.onResume();
    }

    private void showTextWhenNone(Boolean show) {
        if (show) {
            if (aroundList.getVisibility() == View.VISIBLE) {
                aroundList.setVisibility(View.GONE);
            }
            if (none.getVisibility() == View.GONE) {
                none.setVisibility(View.VISIBLE);
            }
        } else {
            if (aroundList.getVisibility() == View.GONE) {
                aroundList.setVisibility(View.VISIBLE);
            }
            if (none.getVisibility() == View.VISIBLE) {
                none.setVisibility(View.GONE);
            }
        }
    }

    @OnClick(R.id.around_map_item)
    protected void onMapListClick(View view) {
        if (repairShopListAdapter.getData().size() > 0) {
            BDLocation l = locationClient.getLastKnownLocation();

            double lat = l.getLatitude();
            double lon = l.getLongitude();

            Intent intent = new Intent();
            intent.putExtra("lon", lon);
            intent.putExtra("lat", lat);
            intent.putExtra("zoom", 16);
            intent.putExtra("points", (Serializable) repairShopListAdapter.getData());
            intent.setClass(AroundMainActivity.this, MapActivity.class);
            startActivity(intent);
        }
    }

    private BDLocationListener bdLocationLinstener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (location == null)
                location = locationClient.getLastKnownLocation();
            else
            	getCar91Application().setLocating(true);
            
            lat = location.getLatitude();
            lon = location.getLongitude();

            addDate = false;
            aroundPager.reset();

            getData();
            //Car91HttpUtil.AsyncHttp(getCar91Application().getAndroidServerUrl()+"/around.action", params, callBack, HttpMethod.POST);
        }


    };

    RequestCallBack callRepairShopBack = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub
            Toast.makeText(AroundMainActivity.this, "网络异常", Toast.LENGTH_LONG).show();
            onStopLoad();
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            List<RepairShop> repairShops = Car91JsonUtil.getDTOList(arg0.result.toString(), RepairShop.class);
            onStopLoad();
            if (repairShops.size() > 0) {
                showTextWhenNone(false);
                if (addDate) {
                    repairShopListAdapter.addData(repairShops);
                } else {
                    repairShopListAdapter.setData(repairShops);
                }
                addDate = !addDate;
                repairShopListAdapter.notifyDataSetChanged();
                option.setScanSpan(getCar91Application().UPDATE_TIME_LONG);
                locationClient.setLocOption(option);
            } else if (!addDate) {
                showTextWhenNone(true);
            } else {
                aroundList.getmFooterView().getmHintView().setText(getResources().getString(R.string.xlistview_footer_hint_nomore));
            }
        }
    };

    public void getData() {
    	if(lat==null||lon==null){
    		locationClient.requestOfflineLocation();
    		new Builder(this).setMessage("正在定位您的位置，请稍后").create().show();
    		return;
    	}
        Location myLocation = EarthUtil.getLocationRadius(lat, lon, 200f);//200km范围内

        aroundPager.getPublicData(lat, lon, myLocation.lat, myLocation.lon, callRepairShopBack);
    }

    @OnItemClick(R.id.around_list)
    public void onItemClickListener(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
        // TODO Auto-generated method stub
        String rid = repairShopListAdapter.getRepairShopId(arg2-1);

        Intent intent = new Intent();
        intent.putExtra("rid", rid);
        intent.setClass(AroundMainActivity.this, RepairShopDetailActivity.class);
        startActivity(intent);
    }

    private BroadcastReceiver itemChangeBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            int item = arg1.getIntExtra("curItem", Item.CB_INDEX_repairshop);

            if (item == Item.CB_INDEX_around) {
                option.setScanSpan(getCar91Application().UPDATE_TIME_SHORT);
                locationClient.setLocOption(option);
                if (!locationClient.isStarted()) {
                    locationClient.start();
                    locationClient.registerLocationListener(bdLocationLinstener);
                }
            } else {
                option.setScanSpan(getCar91Application().UPDATE_TIME_SUPER_LONG);
                locationClient.setLocOption(option);
                if (locationClient.isStarted())
                    locationClient.stop();
                try {
                    locationClient.unRegisterLocationListener(bdLocationLinstener);
                } catch (Exception e) {
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (locationClient.isStarted()) {
            locationClient.stop();
        }
        unregisterReceiver(itemChangeBroadcastReceiver);
        try {
            locationClient.unRegisterLocationListener(bdLocationLinstener);
        } catch (Exception e) {
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        if (locationClient.isStarted()) {
            locationClient.stop();
        }
        super.onBackPressed();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        if (locationClient.isStarted()) {
            locationClient.stop();
        }
        super.onStop();
    }
}
